package com.damai.action.json;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.citywithincity.utils.ClassUtil;
import com.damai.error.ApiError;

class ListParamParser implements IParamGetter {
	

	
	private String name;
	private Class<?> type;
	private Field[] fields;
	public ListParamParser(String name,Class<?> type) {
		this.name = name;
		this.type = type;
		fields = ClassUtil.getFields(type);
		for (Field field : fields) {
			field.setAccessible(true);
		}
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
	public Object get(Map<String, Object> param)  {
		final String name = this.name;
		final Field[] fields = this.fields;
		List<Map<String, Object>> data = (List<Map<String, Object>>) param.get(name);
		try{
			List result = new ArrayList(data.size());
			for (Map<String, Object> map : data) {
				Object obj = type.newInstance();
				for (Field field : fields) {
					
					String fn = field.getName();
					if(map.containsKey(fn)){
						
						field.set(obj, map.get(fn));;
						
					}
				}
				result.add(obj);
			}

			return result;
		}catch(Exception e){
			throw new ApiError("参数错误:["+name+"]"+e.getMessage());
		}
		
	}

}
